package com.emmm.emmm

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.webkit.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat.startActivity
import com.ejlchina.json.JSONKit
import com.ejlchina.okhttps.HTTP
import com.ejlchina.okhttps.HttpResult
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import okhttp3.Headers
import okhttp3.OkHttpClient
import okio.IOException
import org.json.JSONException
import org.json.JSONObject
import java.util.*
import kotlin.collections.HashMap


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val web = WebView(this)
        setContentView(web)
        web.webViewClient= object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                return super.shouldOverrideUrlLoading(view, request)
            }
        }
        web.settings.javaScriptEnabled=true
        web.settings.useWideViewPort=true
        web.settings.loadWithOverviewMode=true
        web.settings.domStorageEnabled=true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            web.settings.safeBrowsingEnabled=false
        }
        web.settings.allowFileAccess=true
        web.settings.allowContentAccess=true
        web.settings.allowUniversalAccessFromFileURLs=true
        web.settings.allowFileAccessFromFileURLs=true
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            WebView.setWebContentsDebuggingEnabled(true)
        }
        val cookieManager: CookieManager = CookieManager.getInstance()
        cookieManager.setAcceptCookie(true) // 允许接受 Cookie

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.setAcceptThirdPartyCookies(web, true) //跨域cookie读取
        }
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush()
        }
        web.addJavascriptInterface(WebAppInterface(this, web), "APP")
        web.loadUrl("file:///android_asset/html/index.html")
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent != null) {
            val isExit = intent.getBooleanExtra("exit", false)
            if (isExit) {
                finish()
            }
        }
    }

    class WebAppInterface(private val mContext: Context, private val web: WebView) {

        /** 为JS提供方法  */
        @JavascriptInterface
        fun quit() {
            val intent = Intent(mContext, MainActivity::class.java)
            intent.putExtra("exit", true)
            startActivity(mContext, intent, Bundle())
        }

        @JavascriptInterface
        fun isAAPP(): Boolean {
            return true
        }

        fun jsonToMap(jsonStr: String?): Map<String, String?>? {
            if (null == jsonStr) {
                return null
            }
            val map: MutableMap<String, String?> = HashMap()
            val s = jsonStr.replace("\"", "").replace("{", "").replace("}", "").split(",").toTypedArray()
            for (st in s) {
                val s1 = st.split(":").toTypedArray()
                if (s1.size == 3) {
                    map[s1[0]] = null
                    map[s1[1]] = s1[2]
                    continue
                }
                if (s1.size == 2) {
                    map[s1[0]] = s1[1]
                }
            }
            return map
        }

        @JavascriptInterface
        fun httpRequest(jsonStr: String) {
            Handler(Looper.getMainLooper()).post(Runnable {
                // code goes here
                try {
                    val json = JSONObject(jsonStr)
                    val http = HTTP.builder()
                            .config { b: OkHttpClient.Builder -> b.cookieJar(PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(mContext))) }
                            .build()
                    var httpT=http.async(json.get("地址") as String?)
                            .addHeader(this.jsonToMap(json.get("headers") as String?))
                    if (json.get("方法")=="POST") {
                        httpT=httpT.addBodyPara(this.jsonToMap(json.get("报文体") as String?))
                    }
                    httpT.setOnResponse { res: HttpResult ->
                        Handler(Looper.getMainLooper()).post(Runnable {
                            // 响应回调
                            val status: Int = res.status // 状态码
                            //val headers: Headers = res.headers // 响应头
                            val body: HttpResult.Body = res.body // 报文体
                            var result= HashMap<String,String?>()
                            result["状态"] = "完成后"
                            result["是否成功"]="true"
                            result["状态码"]=status.toString()
                            result["内容"] = body.toString()
                            result["url"] = res.response.request.url.toString()

                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                                //web.evaluateJavascript("请求回调("+json.get("index")+",\"完成后\")", ValueCallback {})
                                web.evaluateJavascript("请求回调(" + json.get("index") + ",\"" + JSONKit.toJson(result).toString().replace("\\","\\\\").replace("\"","\\\"") + "\")", ValueCallback {})
                                //print(body.toString())
                            }
                        })
                    }
                    .setOnException { e: IOException? ->
                        //异常回调
                    }
                    .setOnComplete { state: HttpResult.State? ->
                        Handler(Looper.getMainLooper()).post(Runnable {
                            //完成回调
                            if (state == HttpResult.State.TIMEOUT) {
                                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                                    web.evaluateJavascript("请求回调(" + json.get("index") + ",\"超时\")", ValueCallback {})
                                }
                            }
                        })
                    }
                    .request(json.get("方法") as String?)
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            })
        }
    }
}